//
//  UIScrollView+windmill.m
//  ExcellentHome
//
//  Created by mac on 2017/12/14.
//  Copyright © 2017年 陈区. All rights reserved.
//

#import "UIScrollView+windmill.h"
#import "SEGWindmillProperty.h"
#import <objc/message.h>
#import "SEGSEGBasicKitLayoutDefine.h"
#define msgWindmillSend(...) ((void (*)(void *, SEL, UIView *))objc_msgSend)(__VA_ARGS__)
CGFloat footerCanFreshSize = 60.0;

@implementation UIScrollView (windmill)
-(void)addWindmillInSuperView:(UIView *)superView
{
    
    //mj的刷新禁止使用此方法，非mj请一定使用此方法
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    windmillvar.isMJRefresh = NO;
    [windmillvar.refreshbgView removeFromSuperview];
    [windmillvar.pullRefreshViews removeFromSuperview];
    [windmillvar.pullRefreshLabel removeFromSuperview];
    [self addHeaderInSuperView:superView];
    [self addFooterInSuperView:superView];
    
    self.width
}

-(void)addHeaderInSuperView:(UIView *)superView
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    windmillvar.showHeader = YES;
    windmillvar.isFooter = NO;
    windmillvar.isMJRefresh = NO;
    windmillvar.takeWindmillToFront = NO;
    
    UIImageView * refreshbgView = windmillvar.refreshbgView;
    BOOL canMoveSun = windmillvar.canMoveSun;
    BOOL canHeaderFresh = windmillvar.canHeaderFresh;
    
    canMoveSun=YES;
    canHeaderFresh = NO;
    
    [self addSubview:refreshbgView];
    
    windmillvar.refreshbgView = refreshbgView;
    windmillvar.canMoveSun = canMoveSun;
    windmillvar.canHeaderFresh = canHeaderFresh;
    self.backgroundColor = [UIColor clearColor];
//    [self justStartAnimatingWindmill];
    if (superView.backgroundColor != kColor_bg &&
        superView.backgroundColor != kColor_bg2 &&
        superView.backgroundColor != kColor_bg2 &&
        superView.backgroundColor != kColor_bg3 &&
        superView.backgroundColor != kColor_bg) {
        superView.backgroundColor = kColor_bg;
    }
    [self recordShowHeaderAndShowFooter];
}

-(void)addFooterInSuperView:(UIView *)superView
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    windmillvar.showFooter = YES;
    windmillvar.isMJRefresh = NO;
    windmillvar.stopFooterRefreshData = NO;//默认为no可加载
    windmillvar.takeFooterRefreshToFront = NO;
    
    UIImageView * pullRefreshViews = windmillvar.pullRefreshViews;
    UILabel * pullRefreshLabel = windmillvar.pullRefreshLabel;
    BOOL canHeaderFresh = windmillvar.canHeaderFresh;

    [superView addSubview:pullRefreshViews];
    [superView addSubview:pullRefreshLabel];
    [pullRefreshViews sizeToFit];
    [pullRefreshLabel sizeToFit];
    
    CGFloat X = (ScreenWidth - (CGRectGetWidth(pullRefreshLabel.frame) + 6 + CGRectGetWidth(pullRefreshViews.frame))) * 0.5;
    
    pullRefreshViews.frame  = CGRectMake(X,
                                         self.frame.origin.y+self.frame.size.height - CGRectGetHeight(pullRefreshLabel.frame)  - footerCanFreshSize,
                                         CGRectGetWidth(pullRefreshViews.frame),
                                         CGRectGetHeight(pullRefreshViews.frame));
    
    pullRefreshLabel.frame  = CGRectMake(
                                         CGRectGetMaxX(pullRefreshViews.frame) + 6,
                                         CGRectGetMinY(pullRefreshViews.frame) + (CGRectGetHeight(pullRefreshViews.frame) - CGRectGetHeight(pullRefreshLabel.frame)) * 0.5,
                                         CGRectGetWidth(pullRefreshLabel.frame),
                                         CGRectGetHeight(pullRefreshLabel.frame));
    pullRefreshLabel.hidden = YES;
    pullRefreshViews.hidden = YES;
    
    windmillvar.pullRefreshViews = pullRefreshViews;
    windmillvar.pullRefreshLabel = pullRefreshLabel;
    windmillvar.canHeaderFresh = canHeaderFresh;
    [windmillvar.pullRefreshViews startAnimating];
    if (windmillvar.takeFooterRefreshToFront) {
        [superView bringSubviewToFront:windmillvar.pullRefreshViews];
        [superView bringSubviewToFront:windmillvar.pullRefreshLabel];
    }else{
        [superView insertSubview:windmillvar.pullRefreshViews atIndex:0];
        [superView insertSubview:windmillvar.pullRefreshLabel atIndex:0];
    }

    self.backgroundColor = [UIColor clearColor];
    if (superView.backgroundColor != kColor_bg &&
        superView.backgroundColor != kColor_bg2 &&
        superView.backgroundColor != kColor_bg2 &&
        superView.backgroundColor != kColor_bg3 &&
        superView.backgroundColor != kColor_bg) {
        superView.backgroundColor = kColor_bg;
    }
    [self recordShowHeaderAndShowFooter];
}

-(void)justShowHeader
{
    
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    windmillvar.showHeader = YES;
    windmillvar.showFooter = NO;
    [windmillvar.pullRefreshViews removeFromSuperview];
    [windmillvar.pullRefreshLabel removeFromSuperview];
    [self recordShowHeaderAndShowFooter];
}

-(void)justShowfooter
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    windmillvar.showHeader = NO;
    windmillvar.showFooter = YES;
    [windmillvar.refreshbgView removeFromSuperview];
    [self recordShowHeaderAndShowFooter];
}

-(void)recordShowHeaderAndShowFooter
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    UIViewController * refreshingTaget = self.superview.viewController;
    if (refreshingTaget) {
        NSString * className = NSStringFromClass([refreshingTaget class]);
        NSArray * data = @[
                           windmillvar.showHeader?@"1":@"0",
                           windmillvar.showFooter?@"1":@"0",
                           windmillvar.isMJRefresh?@"1":@"0"
                           ];
        if (!windmillvar.showHeaderAndShowFooterDict) {
            windmillvar.showHeaderAndShowFooterDict = [[NSMutableDictionary alloc] init];
        }
        [windmillvar.showHeaderAndShowFooterDict setObject:data forKey:className];
    }
}

-(void)startAnimatingWindmill:(void(^)(BOOL canHeaderFresh, BOOL isFooter))canfreshBlock
{
    [SVProgressHUD dismiss];//不需要菊花
    //一般在scrollViewWillEndDragging:withVelocity:targetContentOffset:中调用
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    if ( ! windmillvar.isUserTouched && windmillvar.isFooter) {
        return;
    }
    BOOL isJustShowFooter = NO;
    if (!windmillvar.showHeader && windmillvar.showFooter) {
        isJustShowFooter = YES;
    }
    if (!windmillvar.isFooter) {//下拉刷新时设置
        [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"isWindmillRefreshAction"];
    }

    [windmillvar startLoadData];
    if(windmillvar.canHeaderFresh) windmillvar.isLoading = YES;
    canfreshBlock(windmillvar.canHeaderFresh,windmillvar.isFooter);
    [self limitTimeWithSecond:1.5];
    windmillvar.isUserTouched = NO;
    windmillvar.canHeaderFresh = NO;
}

-(void)limitTimeWithSecond:(NSInteger)second
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    if (windmillvar.isFooter) {
        [self stopAnimatingWindmill];
    }
    //second秒极限
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(second * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (windmillvar.isLoading) {
            [self stopAnimatingWindmill];
        }
    });
}

-(void)stopAnimatingWindmill
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    
    windmillvar.canHeaderFresh = NO;
    windmillvar.isLoading = NO;

    if (!windmillvar.isFooter) {//下拉刷新时需要
        UIEdgeInsets scrollInset = self.contentInset;
        CGFloat insetTop = scrollInset.top;
        [UIView animateWithDuration:0.5 animations:^{
            self.contentOffset = CGPointMake(self.contentOffset.x, -insetTop);
        }];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        windmillvar.stopFooterRefreshData = NO;//停止大风车动画后1秒，再此允许上拉可加载
        [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:@"isWindmillRefreshAction"];
    });
 //在调用scrollViewDidScroll时执行draggingScrollViewInOffsety方法，会在方法中判断停止动画时机并停止动画
}

-(void)draggingScrollViewInOffsety:(CGFloat)offsety
{
    UIEdgeInsets scrollInset = self.contentInset;
    CGFloat insetTop = scrollInset.top;
    //纠正offsety，有时候有的scrollview会设置contentInset.top不为0。
    CGFloat correctOffsety = offsety + insetTop;
    //在调用scrollViewDidScroll时,一定要执行draggingScrollViewInOffsety方法
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    if (self.isTracking && !windmillvar.isUserTouched && windmillvar.canHeaderFresh) {
        windmillvar.isUserTouched = YES;
    }
    
    if (windmillvar.showHeaderAndShowFooterDict) {
        //由于是单例，所以要取存储的数据来判断是不是要显示头部或者底部
        UIViewController * refreshingTaget = self.superview.viewController;
        if (refreshingTaget) {
            NSString * className = NSStringFromClass([refreshingTaget class]);
            if ([windmillvar.showHeaderAndShowFooterDict.allKeys containsObject:className]) {
                NSArray * dataValueForShow = windmillvar.showHeaderAndShowFooterDict[className];
                BOOL isShowHeader = [dataValueForShow.firstObject boolValue];
                BOOL isShowFooter = [dataValueForShow[1] boolValue];
                BOOL isMJRefresh = [dataValueForShow[2] boolValue];
                if (isShowHeader != windmillvar.showHeader) {
                    windmillvar.showHeader = isShowHeader;
                }
                if (isShowFooter != windmillvar.showFooter) {
                    windmillvar.showFooter = isShowFooter;
                }
                //修复使用MJRefresh的界面偶现不能刷新问题 Wendy
                if (isMJRefresh != windmillvar.isMJRefresh) {
                    windmillvar.isMJRefresh = isMJRefresh;
                }
            }

        }
    }

    if (correctOffsety<=0) {
        //下拉刷新
        if (!windmillvar.showHeader) {
            windmillvar.canHeaderFresh = NO;
            return;
        }
        
        windmillvar.isFooter = NO;
        
        if (windmillvar.isLoading) {
            self.contentOffset = CGPointMake(self.contentOffset.x, 0 - CGRectGetHeight(windmillvar.refreshbgView.frame)-insetTop);
        }
        if (windmillvar.canMoveSun) {
            [windmillvar animationBeforeRefesh:correctOffsety];
        }
        
        if((0 - correctOffsety) >= CGRectGetHeight(windmillvar.refreshbgView.frame) && self.isTracking) {
            windmillvar.canHeaderFresh = YES;
            windmillvar.canMoveSun = NO;
            // !!!:如果需要下拉到某处时，界面卡在某处不再随手指滑动，请打开此注释代码
            //self.contentOffset = CGPointMake(self.contentOffset.x, 0 - CGRectGetHeight(windmillvar.refreshbgView.frame)-insetTop);
            
        }else if (correctOffsety == 0 && !windmillvar.canHeaderFresh){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                windmillvar.canMoveSun = YES;
            });
        }

    }else{
        //上拉加载
        if (!windmillvar.showFooter) {
            windmillvar.canHeaderFresh = NO;
            return;
        }
        windmillvar.isFooter = YES;
        CGFloat canFreshSize = footerCanFreshSize-10;//上拉到何处可以刷新
        CGFloat maxOffsety = self.contentSize.height-self.frame.size.height+insetTop;//本来scroll的最大的距离
        // 解决collection滚动到底部 底部刷新控件一直不消失的问题
        if ([self isKindOfClass:[UICollectionView class]]) {
            maxOffsety += canFreshSize;
        }
        if (correctOffsety > maxOffsety) {
            windmillvar.pullRefreshLabel.hidden = NO;
            windmillvar.pullRefreshViews.hidden = NO;
        }else{
            windmillvar.pullRefreshLabel.hidden = YES;
            windmillvar.pullRefreshViews.hidden = YES;
        }
        if (maxOffsety<0 && correctOffsety<footerCanFreshSize) {//数据太少，又没有上拉，不显示
            windmillvar.pullRefreshLabel.hidden = YES;
            windmillvar.pullRefreshViews.hidden = YES;
        }

        
        if (correctOffsety > maxOffsety+canFreshSize && !windmillvar.stopFooterRefreshData) {
            windmillvar.canHeaderFresh = YES;
        }
        if(correctOffsety <= maxOffsety +canFreshSize || maxOffsety<0 || maxOffsety==0){//小于或者等于0属于tableview太短bug
            windmillvar.canHeaderFresh = NO;
        }
    }

    //mjrefresh相关
    if (windmillvar.refreshbgView.superview != self) {
        windmillvar.beginRefreshingTaget = self.superview.viewController;
        windmillvar.beginDownloadingTaget = self.superview.viewController;
    }
    

    //大风车位置相关，与动画无关，一般在有左右滑动的视图时，大风车的位置需要需要重新布置，所以有以下代码
    if (windmillvar.showHeader)
    {
        [self insertSubview:windmillvar.refreshbgView atIndex:0];
    }
    if (windmillvar.showFooter){
        [windmillvar.pullRefreshViews.superview insertSubview:windmillvar.pullRefreshViews atIndex:0];
        [windmillvar.pullRefreshLabel.superview insertSubview:windmillvar.pullRefreshLabel atIndex:0];
        CGFloat heightScrollviewPointY = self.frame.origin.y+self.frame.size.height;
        windmillvar.pullRefreshViews.top = heightScrollviewPointY - CGRectGetHeight(windmillvar.pullRefreshLabel.frame)  - footerCanFreshSize;
        windmillvar.pullRefreshLabel.top = CGRectGetMinY(windmillvar.pullRefreshViews.frame) + (CGRectGetHeight(windmillvar.pullRefreshViews.frame) - CGRectGetHeight(windmillvar.pullRefreshLabel.frame)) * 0.5;
    }
    if (windmillvar.takeWindmillToFront) {
        [windmillvar.refreshbgView.superview bringSubviewToFront:windmillvar.refreshbgView];
    }
    if (windmillvar.takeFooterRefreshToFront) {
        [windmillvar.pullRefreshViews.superview bringSubviewToFront:windmillvar.pullRefreshViews];
        [windmillvar.pullRefreshLabel.superview bringSubviewToFront:windmillvar.pullRefreshLabel];
    }

    //mjrefresh相关
    if (windmillvar.isMJRefresh && !self.isTracking && windmillvar.canHeaderFresh) {//松手才刷新
        [self startAnimatingWindmill:^(BOOL canHeaderFresh, BOOL isFooter) {
            if (canHeaderFresh) {
                if (isFooter && !windmillvar.stopFooterRefreshData) {
                    windmillvar.stopFooterRefreshData = YES;//不允许上拉加载,防止重复加载
                    [self segWindmillStartAction];
                }
                else if (!isFooter) {
                    [self segWindmillStartAction];
                }
            }
        }];
    }
}

-(void)justStartAnimatingWindmill
{
    //只需要刷新动画，不需要数据刷新
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    windmillvar.isFooter = NO;

    [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"isWindmillRefreshAction"];

    UIEdgeInsets scrollInset = self.contentInset;
    CGFloat insetTop = scrollInset.top;
    if (self.contentOffset.y+insetTop>=0) {
        self.contentOffset = CGPointMake(self.contentOffset.x, -windmillvar.refreshbgView.frame.size.height-1-insetTop);
    }
    [windmillvar startLoadData];//刷新转圈动画
    [self limitTimeWithSecond:1.5];
}

-(void)showWindMillInUnclearBackColorView
{
    //在有背景色的tableview中显示大风车刷新效果
    //此处将大风车放在视图最前面，再通过clipsToBounds==yes属性，会将大风车视图在视觉上切掉，造成大风车在tableView后面的假象，可以满足一些有背景色的tableView也可以看见大风车刷新效果。clipsToBounds已默认为YES
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    [windmillvar.refreshbgView.superview bringSubviewToFront:windmillvar.refreshbgView];
    [windmillvar.pullRefreshViews.superview bringSubviewToFront:windmillvar.pullRefreshViews];
    [windmillvar.pullRefreshLabel.superview bringSubviewToFront:windmillvar.pullRefreshLabel];

    windmillvar.takeWindmillToFront = YES;
    windmillvar.takeFooterRefreshToFront = YES;
}
#pragma mark- 为了配合之前UIScrollView+MJRefresh的方法特别增加的方法，如果不用UIScrollView+MJRefresh则忽略以下代码
-(void)segWindmillSetTarget:(id)target action:(SEL)action
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    windmillvar.beginRefreshingTaget = target;
    windmillvar.beginRefreshingAction = action;
}

-(void)segWindmillSetRefreshBlock:(void(^)())callback
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    windmillvar.beginRefreshingCallback = callback;
}

-(void)segWindmillSetFooterBlock:(void(^)())callback
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    windmillvar.beginDownloadingCallback = callback;
}

-(void)segWindmillSetFooterTarget:(id)target action:(SEL)action
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    windmillvar.beginDownloadingTaget = target;
    windmillvar.beginDownloadingAction = action;
}

-(void)segWindmillStartAction
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    if (!windmillvar.canHeaderFresh) {
        return;
    }

    if (windmillvar.isFooter) {
        if ([windmillvar.beginDownloadingTaget respondsToSelector:windmillvar.beginDownloadingAction]) {
            msgWindmillSend((__bridge void *)(windmillvar.beginDownloadingTaget), windmillvar.beginDownloadingAction, self);
        }
        
        if (windmillvar.beginDownloadingCallback) {
            windmillvar.beginDownloadingCallback();
        }

    }else{
        if ([windmillvar.beginRefreshingTaget respondsToSelector:windmillvar.beginRefreshingAction]) {
            msgWindmillSend((__bridge void *)(windmillvar.beginRefreshingTaget), windmillvar.beginRefreshingAction, self);
        }
        
        if (windmillvar.beginRefreshingCallback) {
            windmillvar.beginRefreshingCallback();
        }
    }
    windmillvar.canHeaderFresh = NO;
}

-(void)checkActionForShowView
{
    //tips:默认状态下header和footer是显示的,如果没有实现刷新的方法就不显示相应的刷新
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    BOOL showFooter = NO;
    if ([windmillvar.beginDownloadingTaget respondsToSelector:windmillvar.beginDownloadingAction]) {
        showFooter = YES;
    }
    if (windmillvar.beginDownloadingCallback) {
        showFooter = YES;
    }

    BOOL showHeader = NO;
    if ([windmillvar.beginRefreshingTaget respondsToSelector:windmillvar.beginRefreshingAction]) {
        showHeader = YES;
    }
    
    if (windmillvar.beginRefreshingCallback) {
        showHeader = YES;
    }

    if (!showHeader && showFooter) [self justShowfooter];
    if (!showFooter && showHeader) [self justShowHeader];
    if (!showFooter && !showHeader) {
        SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
        windmillvar.showHeader = NO;
        windmillvar.showFooter = NO;
        [windmillvar.refreshbgView removeFromSuperview];
        [windmillvar.pullRefreshViews removeFromSuperview];
        [windmillvar.pullRefreshLabel removeFromSuperview];
    }
}

-(BOOL)isCanrefresh
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    return windmillvar.canHeaderFresh;
}

-(void)canrefreshAction
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    windmillvar.canHeaderFresh = YES;
    windmillvar.isFooter = NO;
}

-(CGFloat)windmillHeight
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    return windmillvar.refreshbgView.frame.size.height;
}

//只适用于使用了UIScrollView+MJRefresh,使用时一定要放在addHeaderInSuperView和addFooterInSuperView之后
-(void)isMjRefresh
{
    SEGWindmillProperty * windmillvar = [SEGWindmillProperty sharedWindmillVar];
    windmillvar.isMJRefresh = YES;
}
@end
